// speed_chart_page.dart\
import 'dart:async';

import 'package:syncfusion_flutter_charts/charts.dart';
import 'package:speedometer/speed_chart_page.dart';
import 'package:flutter/material.dart';

// 定义全局 key
final GlobalKey<_SpeedChartPageState> speedChartKey = GlobalKey<_SpeedChartPageState>();

class SpeedChartPage extends StatefulWidget {
  const SpeedChartPage({Key? key}) : super(key: key);

  @override
  State<SpeedChartPage> createState() => _SpeedChartPageState();
}

class _SpeedChartPageState extends State<SpeedChartPage> {
  final List<SpeedPoint> _points = [];
  Timer? _timer;
  static const wheelCircumference = 2.105; // 轮周长，单位米

  @override
  void initState() {
    super.initState();
    // 每秒清理老数据并重绘
    _timer = Timer.periodic(const Duration(seconds: 1), (_) {
      final cutoff = DateTime.now().subtract(const Duration(seconds: 15));
      setState(() => _points.removeWhere((p) => p.ts.isBefore(cutoff)));
    });
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  // 外部调用入口
  void addRawData(int deltaRev, double deltaTimeSec) {
    if (deltaTimeSec <= 0) return;
    final speed = wheelCircumference * deltaRev / deltaTimeSec;
    setState(() => _points.add(SpeedPoint(DateTime.now(), speed)));
  }

  double get _currentSpeed => _points.isEmpty ? 0 : _points.last.speedMs;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: Column(
        children: [
          Expanded(
            flex: 2,
            child: Center(
              child: Text(
                '${_currentSpeed.toStringAsFixed(2)} m/s',
                style: const TextStyle(
                    fontSize: 72,
                    fontWeight: FontWeight.bold,
                    color: Colors.white),
              ),
            ),
          ),
          Expanded(
            flex: 3,
            child: SfCartesianChart(
              plotAreaBorderWidth: 0,
              primaryXAxis: DateTimeAxis(
                isVisible: false,
                intervalType: DateTimeIntervalType.seconds,
              ),
              primaryYAxis: NumericAxis(
                title: const AxisTitle(text: 'Speed (m/s)'),
                labelStyle: const TextStyle(color: Colors.white),
              ),
              series: <LineSeries<SpeedPoint, DateTime>>[
                LineSeries<SpeedPoint, DateTime>(
                  dataSource: _points,
                  xValueMapper: (p, _) => p.ts,
                  yValueMapper: (p, _) => p.speedMs,
                  color: Colors.cyanAccent,
                  width: 3,
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

// 车速数据点
class SpeedPoint {
  final DateTime ts;
  final double speedMs;
  SpeedPoint(this.ts, this.speedMs);
}